package com.haoxuewa.controller;

import com.haoxuewa.dao.EssayDao;
import com.haoxuewa.dao.EssayTempDao;
import com.haoxuewa.entity.Admin;
import com.haoxuewa.service.AdminService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/backstage")
public class AdminController {

    private final AdminService adminService;

    @Autowired
    public AdminController(AdminService adminService) {
        this.adminService = adminService;
    }

    @PostMapping("/adminLogin")
    public String adminLogin(@RequestBody Map<String, String> map, HttpSession session) {
        String name = map.get("name");
        String password = map.get("password");
        Admin admin = adminService.adminLogin(name, password);
        JSONObject jsonObject = new JSONObject();
        if (admin != null) {
            session.setAttribute("SYSTEM_ADMIN_SESSION", admin);   //网站维护一个管理员登录的会话
            jsonObject.put("code", "200");
        } else {
            jsonObject.put("code", "404");
        }
        return jsonObject.toString();
    }

    //添加管理员
    @PostMapping("/addAdmin")
    public String addAdmin(@RequestBody Map<String, String> adminInfo) {
        JSONObject jsonObject = new JSONObject();
        Admin admin = adminService.selectAdminsByName(adminInfo.get("name"));
        if (Objects.isNull(admin))
            if (adminService.addAdmin(adminInfo.get("name"), adminInfo.get("password")))
                jsonObject.put("result", "管理员添加成功！");
            else jsonObject.put("result", "系统异常添加失败");
        else
            jsonObject.put("result", "管理员已存在，添加失败！");
        return jsonObject.toString();
    }
}
